package cn.ac.iie.di.wx.mq.killHandler;

import cn.ac.iie.di.datadock.rdata.exchange.client.v1.REMessage;
import cn.ac.iie.di.datadock.rdata.exchange.client.v1.connection.REConnection;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
import sun.misc.Signal;
import sun.misc.SignalHandler;

/**
 * @author zmc <zhangmingcheng@iie.ac.cn>
 * @date 2016-9-7 14:32:27
 * @version V1.0
 * @desc
 */
public class KillHandler implements SignalHandler {

    public static Logger logger = org.apache.log4j.Logger.getLogger(KillHandler.class.getName());
    private List<REConnection> conns;
//    private ExecutorService pool;
    private Map<String, BlockingQueue> queues = new HashMap<>();
    private ConcurrentHashMap<String, Integer> concurrentHashMap;

    public void registerSignal(String signalName) {
        Signal signal = new Signal(signalName);
        Signal.handle(signal, this);
    }

    @Override
    public void handle(Signal signal) {
        logger.info("now receive the system signal " + signal.getName() + " " + signal.getNumber() + "\n\n");
        if (signal.getName().equals("TERM")) {
            try {
                for (REConnection conn : conns) {
                    conn.close();
                }
                logger.info("shutdown mq connection ...");
                checkQueues();
                logger.info("shutdown send queue...");
            } catch (Exception ex) {
                logger.error("Program shudown error!", ex);
            } finally {
                logger.info("Program has shutdown !");
                System.exit(0);
            }
        } else if (signal.getName().equals("INT") || signal.getName().equals("HUP")) {
            System.exit(0);
        } else {
            logger.info("can not process the system signal " + signal.toString());
        }
    }

    public void handleHashMap(ConcurrentHashMap<String, Integer> concurrentHashMap) {
        //写入文件中
        String uidStr = "";
        for (Entry<String, Integer> entrySet : concurrentHashMap.entrySet()) {
            String key = entrySet.getKey();
            Integer value = entrySet.getValue();
//            logger.info(key + "---" + value);
            //从哈希表中删除该元素
            concurrentHashMap.remove(key, value);
            uidStr += key + "\n";

        }
        //防止数据长度太大
        if (uidStr.length() >= 1024) {
            String url = System.getProperty("user.dir");
            File file = new File(url + "/uid.txt");
            if (file.exists()) {
                try {
                    //以读写方式打开文件
                    RandomAccessFile accessFile = new RandomAccessFile(file, "rw");
                    accessFile.seek(accessFile.length());
                    accessFile.writeBytes(uidStr);
                    accessFile.close();
                } catch (FileNotFoundException ex) {
                    logger.error(ex.getMessage(), ex);
                } catch (IOException ex) {
                    logger.error(ex.getMessage(), ex);
                }
            } else {
                try {
                    file.createNewFile();
                    RandomAccessFile accessFile = new RandomAccessFile(file, "rw");
                    accessFile.seek(accessFile.length());
                    accessFile.writeBytes(uidStr);
                    accessFile.close();
                } catch (FileNotFoundException ex) {
                    logger.error(ex.getMessage(), ex);
                } catch (IOException ex) {
                    logger.error(ex.getMessage(), ex);
                }
            }
        }

    }

    public void checkQueues() {
        while (true) {
            boolean isEmpty = true;
            for (Entry<String, BlockingQueue> queue : queues.entrySet()) {
                String queueName = queue.getKey();
                BlockingQueue queueObj = queue.getValue();
                int size = queueObj.size();
                if (size != 0) {
                    isEmpty = false;
                    logger.info("the " + queueName + " has " + size + " datas");
                    //清空队列，将去重后的队列数据写入文件中
                    break;
                }
            }
            if (isEmpty) {
                break;
            } else {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ex) {
                }
            }
        }

    }

    public void putQueue(String queueName, BlockingQueue queue) {
        this.queues.put(queueName, queue);
    }

    public ConcurrentHashMap<String, Integer> getConcurrentHashMap() {
        return concurrentHashMap;
    }

    public void setConcurrentHashMap(ConcurrentHashMap<String, Integer> concurrentHashMap) {
        this.concurrentHashMap = concurrentHashMap;
    }

    public void setConns(List<REConnection> conns) {
        this.conns = conns;
    }

}
